// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const userCollection = db.collection('users')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const requestedOpenid = (event && event.openid) || ''
  const openid = requestedOpenid || wxContext.OPENID
  
  if (!openid) {
    return {
      code: -1,
      msg: '获取用户openid失败',
      data: null
    }
  }
  
  try {
    // 查询数据库中的用户信息
    const userResult = await userCollection.where({
      _openid: openid
    }).limit(1).get()
    
    if (userResult.data.length > 0) {
      let userInfo = userResult.data[0] || {}

      // 可选：对调用者自身进行心跳写入（仅当未显式请求他人或 openid 与调用者一致时）
      const canPing = !!event && event.ping === true && (!requestedOpenid || requestedOpenid === wxContext.OPENID)
      if (canPing) {
        try {
          const nowServer = db.serverDate()
          await userCollection.where({ _openid: openid }).update({
            data: {
              lastSeen: nowServer,
              lastLoginTime: nowServer,
              updateTime: nowServer
            }
          })
          // 本地对象用于在线判断（避免再次读取）
          userInfo.lastSeen = new Date()
          userInfo.lastLoginTime = new Date()
        } catch (e) {
          console.error('心跳写入 lastSeen 失败:', e)
        }
      }
      
      // 规范化头像：支持 cloud:// fileID 转临时URL，过滤历史 /assets 路径；同时刷新过期的 tcb 临时 https
      let finalAvatarUrl = userInfo.avatarUrl || userInfo.avatar_url || ''
      let rawAvatarFileId = ''
      if (finalAvatarUrl && typeof finalAvatarUrl === 'string') {
        if (finalAvatarUrl.indexOf('cloud://') === 0) {
          rawAvatarFileId = finalAvatarUrl
          try {
            const tmp = await cloud.getTempFileURL({
              fileList: [finalAvatarUrl]
            });
            if (tmp && tmp.fileList && tmp.fileList[0] && tmp.fileList[0].tempFileURL) {
              finalAvatarUrl = tmp.fileList[0].tempFileURL;
            }
          } catch (e) {
            // 忽略获取临时链接失败，继续使用原值
          }
        } else if (/^https?:\/\/[^\/]+\.tcb\.qcloud\.la\//i.test(finalAvatarUrl)) {
          // 已保存为 tcb 临时 https，尝试还原 fileID 并刷新新的临时链接
          try {
            const m = finalAvatarUrl.match(/^https?:\/\/([^\/]+)\.tcb\.qcloud\.la\/([^?]+)(?:\?|$)/i)
            if (m && m[1] && m[2]) {
              rawAvatarFileId = 'cloud://' + m[1] + '/' + m[2]
              const tmp2 = await cloud.getTempFileURL({ fileList: [rawAvatarFileId] })
              if (tmp2 && tmp2.fileList && tmp2.fileList[0] && tmp2.fileList[0].tempFileURL) {
                finalAvatarUrl = tmp2.fileList[0].tempFileURL
              }
            }
          } catch (e2) {
            // 刷新失败则保留原链接
          }
        }
      }
      if (!finalAvatarUrl || (typeof finalAvatarUrl === 'string' && finalAvatarUrl.indexOf('/assets/') === 0)) {
        finalAvatarUrl = '/static/icons/avatar-placeholder.png';
      }

      // 在线状态判定：优先 lastSeen，回退 lastLoginTime；阈值默认 60s，可由 onlineThresholdMs 覆盖
      const nowTs = Date.now()
      const last = userInfo.lastSeen || userInfo.lastLoginTime || null
      let lastSeenTs = 0
      try {
        if (last) lastSeenTs = new Date(last).getTime()
      } catch (_) {}
      const thresholdMs = (event && Number(event.onlineThresholdMs)) || 60000
      const isOnline = lastSeenTs > 0 && (nowTs - lastSeenTs) <= thresholdMs

      // 返回用户信息（不包含敏感信息）
      return {
        code: 0,
        msg: '获取用户信息成功',
        data: {
          openid: userInfo._openid || openid,
          nickName: userInfo.nickName || '微信用户',
          avatarUrl: finalAvatarUrl,
          rawAvatarFileId: rawAvatarFileId,
          gender: userInfo.gender || 0,
          city: userInfo.city || '',
          province: userInfo.province || '',
          country: userInfo.country || '中国',
          language: userInfo.language || 'zh_CN',
          createTime: userInfo.createTime,
          updateTime: userInfo.updateTime,
          lastLoginTime: userInfo.lastLoginTime || null,
          lastSeen: userInfo.lastSeen || userInfo.lastLoginTime || null,
          isOnline,
          status: isOnline ? 'online' : 'offline'
        }
      }
    } else {
      // 用户不存在
      return {
        code: -1,
        msg: '用户信息不存在，请重新登录',
        data: null
      }
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
    return {
      code: -1,
      msg: '获取用户信息失败',
      error: err
    }
  }
}